package com.kim.rssreader.utils;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;

import com.kim.rssreader.utils.NetUtil.NetProcessComplete;

public class LocationUtil {

	public interface LocationCallback {
		void onLocateSuccess(String[] city);
	}

	Context context;
	LocationCallback callback;

	public LocationUtil(Context ctx, LocationCallback callback) {
		this.context = ctx;
		this.callback = callback;
	}

	public final void updateLocation() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					LocationManager locationManager;
					String serviceName = Context.LOCATION_SERVICE;
					locationManager = (LocationManager) context
							.getSystemService(serviceName);
					String provider = LocationManager.NETWORK_PROVIDER;

					Criteria criteria = new Criteria();
					criteria.setAccuracy(Criteria.ACCURACY_FINE);
					criteria.setAltitudeRequired(false);
					criteria.setBearingRequired(false);
					criteria.setCostAllowed(true);
					criteria.setPowerRequirement(Criteria.POWER_LOW);

					Location location = locationManager
							.getLastKnownLocation(provider);
					updateWithNewLocation(location);
					Looper.prepare();
					locationManager.requestLocationUpdates(provider, 2000, 10,
							locationListener);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}).start();
	}

	public final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}

		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	public void updateWithNewLocation(Location location) {
		// myLocationText = (TextView)findViewById(R.id.txv_show_location);
		if (location != null) {
			final double lat = location.getLatitude();//纬度
			final double lng = location.getLongitude();//经度

			// 根据经纬度获取位置信息
			String[] city = new String[2];
//			city = getAddress( 107.20146939154048, 22.82774540209307);//大新
			city = getAddress(lng, lat);
			callback.onLocateSuccess(city);
			System.out.println("您当前的位置是:" + city);
		}
	}

	public String[] getAddress(Double Longitude, Double Latitude) {
		String url = "http://maps.google.com/maps/api/geocode/json?latlng="
				+ Latitude + "," + Longitude + "&language=zh_CN&sensor=false";
		final StringBuilder sb = new StringBuilder();
		String[] city = new String[2];
		try {
			NetUtil.getInputStream(url, new NetProcessComplete() {

				@Override
				public void onProcess(InputStream inputStream) {
					int len = -1;
					byte[] buf = new byte[1024];
					try {
						while ((len = inputStream.read(buf)) != -1) {
							sb.append(new String(buf, 0, len));
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			JSONObject jo1 = new JSONObject(sb.toString());
			String str1 = jo1.getString("results");
			JSONArray arr1 = new JSONArray(str1);
			String str2 = arr1.get(0).toString();
			JSONObject jo2 = new JSONObject(str2);
//			String str3 = jo2.getString("formatted_address");

			String City_str = jo2.getString("address_components");
			JSONArray city_arr1 = new JSONArray(City_str);
			for(int i = 0 ;i<2 ;i++){
				String city_str2 = city_arr1.get(i+1).toString();//县、区级
//				String city_str2 = city_arr1.get(2).toString();//市级
				JSONObject jo3 = new JSONObject(city_str2);
				String city_str5 = jo3.getString("long_name");
				city[i] = city_str5;
			}
		
			return city;
		} catch (JSONException e) {
			return new String[]{ "", ""};//地址转换失败";
		}

	}

}